# -*- coding: utf-8 -*-

from django import forms
from django.forms.util import ErrorList
from djtools.formfields import BrDataField
from djtools.formwidgets import BrDataWidget
from comum.models import Setor, Estacao
from servico.models import Equipe, ServicoStatus
from django.http import HttpResponse
from geraldo.generators import PDFGenerator
from servico.reports import ServicoInternoReport
#########
# FORMS #
#########

# SERVICOINTERNO #

class RelatorioServicoInternoForm(forms.Form):
    
    fieldsets = [
        (None, {'fields': [('data_inicial','data_final'), 'status', 'setor', 'numero', 'equipe', 'estacao', 'agrupamento']}),
    ]
    
    AGRUPAMENTO = (
            ('', u'Nenhum'),
            ('status', u'Status'),
            ('setor', u'Setor'),
            ('equipe', u'Equipe'),
            ('estacao', u'Estação')
            )
    
    data_inicial = BrDataField(label=u"Período", help_text=u'Data inicial', required=False)
    data_final = BrDataField(help_text=u'Data final', widget=BrDataWidget(show_label=False), required=False)
    status = forms.ModelChoiceField(label=u'Status', queryset=ServicoStatus.objects.all(), empty_label="Todos", required=False)
    setor = forms.ModelChoiceField(label=u'Setor Solicitante', queryset=Setor.objects.all(), empty_label="Todos", required=False)
    numero = forms.CharField(label=u'Número', required=False)
    equipe = forms.ModelChoiceField(label=u'Equipe', queryset=Equipe.objects.all(), empty_label="Todos", required=False)
    estacao = forms.ModelChoiceField(label=u'Estação', queryset=Estacao.objects.all(), empty_label="Todos", required=False)
    agrupamento = forms.ChoiceField(label=u'Agrupar por', widget=forms.Select(), choices=AGRUPAMENTO, required=False)
    
    def clean(self):
        if not self.errors:
            if self.cleaned_data['data_final'] and self.cleaned_data['data_inicial']:
                if self.cleaned_data['data_final'] <= self.cleaned_data['data_inicial']:
                    self._errors['data_final'] = ErrorList([u'A data final deve ser superior a data inicial.'])
                if self.cleaned_data['data_inicial'] >= self.cleaned_data['data_final']:
                    self._errors['data_inicial'] = ErrorList([u'A data inicial deve ser inferior a data final.'])
        return self.cleaned_data
    
    METHOD = 'GET'
    TITLE = 'Gerar Relatório de Serviços Internos'
    
#########
# VIEWS #
#########


def ServicoInternoView(request, servicos):
    
    titulo = 'Relatório de Serviços'
    
    response = HttpResponse(mimetype='application/pdf')
    response['Content-Disposition'] = 'attachment; filename=relatorio.pdf'
    
    report = ServicoInternoReport(queryset=servicos)
    report.generate_by(PDFGenerator, filename=response, variables={'titulo': titulo})

    return response
